package com.gack.business.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gack.business.dao.MessageDao;
import com.gack.business.model.InviteToEnterpriseRecord;
import com.gack.business.model.Message;
import com.gack.business.model.User;
import com.gack.business.model.UserEnterpriseDepartmentPosition;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.InviteToEnterpriseRecordRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserRepository;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.MapAsReturn;

/**
 * 
* @ClassName: MessageService 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author (ZhangXinYu)  
* @date 2018年6月1日 下午3:09:31 
* @version V1.0
 */

@Service
@Transactional
public class MessageService implements MessageServiceInterface{

	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private InviteToEnterpriseRecordRepository inviteToEnterpriseRecordRepository;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private MessageDao messageDao;
	
	@Override
	public Result getUserMessages(String userid, Integer currentPage, Integer pageSize) {
		Result result = new Result();
		User user = userRepository.findOne(userid);
		if(user != null){
			Sort sort = new Sort(Sort.Direction.DESC, "createtime");
			Pageable pageable = new PageRequest(currentPage, pageSize, sort);
			Page<Message> messages = messageRepository.findByUseridAndSendWay(userid,2, pageable);
			if(messages != null){
				result.setKey("success");
				result.setValue(messages);
			}else{
				result.setKey("error_noneMessage");
				result.setMsg("用户暂无消息");
			}
		}else{
			result.setKey("error_noneUser");
			result.setMsg("用户不存在，获取用户消息失败");
		}
		return result;
	}

	@Override
	public Result setMessageRead(String messageId, Integer is_read) {
		Result result = new Result();
		Message message = messageRepository.findOne(messageId);
		if(message == null){
			result.setKey("error_noneMessage");
			result.setMsg("消息不存在，操作失败");
			return result;
		}
		message.setIsRead(is_read);
		message = messageRepository.save(message);
		result.setKey("success");
		result.setValue(message);
		return result;
	}
	
	
	/**
	 * 对"邀请加入公司"类型的消息的处理
	 * @param messageId 消息id
	 * @param operation "agree" "refuse"
	 * @param remarks 备注
	 * @return status:error/success  msg:错误或成功消息
	 */
	@Override
	public Map<String, Object> dealMessage(String messageId, String operation, String remarks) {
		Message message = messageRepository.findOne(messageId);
		
		if(null == message){
			return MapAsReturn.setStatusError("查无此消息");
		}
		
		if(message.getMesType() != 1){
			return MapAsReturn.setStatusError("此条消息类型不正确");
		}
		
		if(message.getState() != 2){
			return MapAsReturn.setStatusError("此条消息已处理过，不能第二次处理");
		}
		
		InviteToEnterpriseRecord iter = inviteToEnterpriseRecordRepository.findOne(message.getDetailId());//获取邀请信息记录表
		
		//若该用户已在该公司内,则不再加入该公司
		if("agree".equals(operation) && userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(message.getUserid(), iter.getEnterpriseId()) > 0){
			return MapAsReturn.setStatusError("您已加入该公司,无法再次加入");
		}
		
		//若同意,则将该用户填入公司,并修改message的相应状态和邀请信息记录表的相应状态
		if(operation.equals("agree")){
			message.setState(1);//修改状态为"同意"
			message.setIsRead(1);//修改状态为"已读"
			messageRepository.save(message);
			
			iter.setStatus(1);//修改邀请信息记录表中记录的状态为"同意"
			inviteToEnterpriseRecordRepository.save(iter);
			
			//将用户填入公司
			UserEnterpriseDepartmentPosition uedp = new UserEnterpriseDepartmentPosition();
			uedp.setUserId(message.getUserid());//设置用户id
			uedp.setEnterpriseId(iter.getEnterpriseId());//设置公司id
			uedp.setEnterpriseRemarks(remarks);//设置企业备注
			uedp.setUpdateTime(new Date());
			userEnterpriseDepartmentPositionRepository.save(uedp);
			
			//将该公司人数加一
			enterpriseRepository.addCurrentNumber(iter.getEnterpriseId());
			
			//修改其他相同邀请且状态为"未处理",置为"不可再次修改"状态
			List<String> detailIdList = inviteToEnterpriseRecordRepository.findIdByEnterpriseIdAndInviteeUsername(2, iter.getEnterpriseId(), iter.getInviteeUsername());
			inviteToEnterpriseRecordRepository.updateStatusByEnterpriseIdAndInviteeUsername(2, 3, iter.getEnterpriseId(), iter.getInviteeUsername());
			messageDao.updateStatusByDetailIds(2, 3, detailIdList);
			
		}else{
			message.setState(0);//修改状态为"拒绝"
			message.setIsRead(1);//修改状态为"已读"
			messageRepository.save(message);
			
			iter.setStatus(0);//修改邀请信息记录表中记录的状态为"拒绝"
			inviteToEnterpriseRecordRepository.save(iter);
		}

		return MapAsReturn.setStatusSuccess(null, null);
	}

	/**
	 * 获取"邀请加入公司"类型的消息的备注
	 * @param messageId 消息id
	 * @return status:error/success  msg:错误或成功消息   remarks:备注
	 */
	@Override
	public Map<String, Object> getRemarksAboutInvitationToEnterprise(String messageId){
		Message message = messageRepository.findOne(messageId);
		
		if(null == message){
			return MapAsReturn.setStatusError("查无此消息");
		}
		
		if(message.getMesType() != 1){
			return MapAsReturn.setStatusError("此条消息类型不正确");
		}
		
		InviteToEnterpriseRecord iter = inviteToEnterpriseRecordRepository.findOne(message.getDetailId());//获取邀请信息记录表
		String remarks = iter.getRemarks();
		return MapAsReturn.setStatusSuccess("remarks", remarks);
	}
	
	/**
	 * 删除消息
	 * @param messageId 消息id
	 * @return status:error/success  msg:错误或成功消息
	 */
	@Override
	public Map<String, Object> deleteMessage(String messageId){
		messageRepository.delete(messageId);
		return MapAsReturn.setStatusSuccess(null, null);
	}
	
	@Override
	public Map<String, Object> getUserStatus(String userid) {
		Map<String, Object> map = new HashMap<>();
		if(userid == null || userid.trim().equals("")){
			map.put("key", "error");
			map.put("msg", "id不可为空");
			map.put("status", -1);
			return map;
		}
		if(userRepository.findOne(userid) == null){
			map.put("key", "error");
			map.put("msg", "用户不存在");
			map.put("status", -1);
			return map;
		}
		int count = messageRepository.getUserStatus(userid);
		map.put("key", "success");
		map.put("msg", "信息状态查询成功");
		map.put("status", (count == 0 ? 0 : 1));
		return map;
	}

	@Override
	public Map<String, Object> updateAllMessageIsRead(String userid, Integer is_read) {
		Map<String, Object> map = new HashMap<>();
		if(userid == null || userid.trim().equals("")){
			map.put("key", "error");
			map.put("msg", "id不可为空");
			return map;
		}
		if(userRepository.findOne(userid) == null){
			map.put("key", "error");
			map.put("msg", "用户不存在");
			return map;
		}
		int count = messageRepository.updateAllMessageIsRead(userid,is_read);
		map.put("key", "success");
		map.put("msg", "状态修改成功");
		map.put("count", messageRepository.getUserStatus(userid));
		return map;
	}
	
}
